<template>
	<view>
		<view v-show="!isShow" style="position: relative; border-radius: 10px;" :style="[{width: `${width}px`, height: `${height}px`, 'margin-left': width==140?'auto':`calc((100% - ${width}px) / 2)`}, {'background-image': bg_url}]" @click="payVideo">
			<image :src="bg_url" class="bg-img" style="width: 100%; border-radius: 10px;" :style="{height: `${height}px`}" mode="aspectFill"></image>

			<image src="/static/chat/open.png" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);" :style="{width: width==140?'32px':'60px', height: height==180?'32px':'60px'}"></image>
		</view>
		<!--  style="width: 142px;height: 180px;z-index: 0" -->
		<!-- #ifdef H5 -->
		<view style="position: relative;" v-show="isShow">
			<video :style="[{width: `${width}px`, height: `${height}px`, 'margin-left': width==140?'auto':`calc((100% - ${width}px) / 2)`}, {'background-image': bg_url}]" :id="refi" :initial-time="initialTime" :show-fullscreen-btn="false" @error="videoErrorCallback"  @fullscreenclick="screenclick" @fullscreenchange="screenchange" @ended="videoEnded" @timeupdate="timeupdate" @pause="videoPause" :src="src" controls x5-video-player-type="h5-page"  webkit-playsinline="true" playsinline="true" x5-video-orientation="landscape|portrait"></video>
			<text @click="closePause()" style="position: absolute; top: 0; right: 0;font-size: 14px;background: #999;padding: 4px 6px;color: #fff;">关闭</text>
		</view>
		<!-- #endif -->
		<!-- #ifdef APP-PLUS -->
		<video v-show="isShow" :style="[{width: `${width}px`, height: `{height}px`, 'margin-left': width==140?'auto':`calc((100% - ${width}px) / 2)`}]" :id="refi" :ref="refi" :initial-time="0"  
			@error="videoErrorCallback"
			@fullscreenclick="screenclick"
			@fullscreenchange="screenchange"
			@ended="videoEnded"
			@pause="videoPause"
			:src="src" controls
		></video>
		<!-- #endif -->
		
		<view id="canvas" class="canvas" :prop="newVal" :change:prop="canvas.create"></view>
	</view>
</template>
<script>
	export default {
		props: {
			src: {
				type: String,
				value: ''
			},
			refi: {
				type: String,
				value: ''
			},
			width: {
				type: Number,
				value: 140
			},
			height: {
				type: Number,
				value: 180
			},
			initialTime: {
				type: Number,
				value: 0
			}
		},
		data() {
			return {
				newVal: null,
				isShow: false,
				videoContext: null,
				src1: '',
				bg_url: '',
				currentTime: 0,
				clickClose: false // 是否点击了关闭按钮
			};
		},
		mounted() {
			this.currentTime = this.initialTime
			// this.src1 = this.src;
			this.videoContext = uni.createVideoContext(this.refi)
			this.$nextTick(()=>{
				
			})
			// #ifdef H5
			getVideoCover(this.src, this)
			// #endif
			
			// #ifdef APP-PLUS
			// this.isShow = true
			getVideoCover(this.src, this)
			// #endif
			
			
		},
	
		methods: {
			videoErrorCallback: function(e) {
				
				// console.log(48, this.src)
				// console.log(383838, e)
			},
			payVideo(){
				this.clickClose = false
				//告诉父组件开始播放,关闭其他播放实例
				this.$emit("playVideo", this.refi);
				//全屏
				// #ifdef APP-PLUS
				this.videoContext.requestFullScreen({direction: 0})
				// #endif
				//开始播放
				this.videoContext.play()
				
				this.isShow = true;
			},
			pauseVideo(){
				this.videoContext.pause()
			},
			videoEnded(){
				this.isShow = false;
				console.log('videoEnded')
				
			},
			closePause(){
				this.clickClose = true;
				this.videoContext.pause()
				this.isShow = false;
			},
			timeupdate(e){
				if(e.detail.duration==e.detail.currentTime){
					this.currentTime = 0
				}else{
					this.currentTime = e.detail.currentTime
				}
				
			},
			videoPause(){
				if(this.clickClose){
					this.$emit('pauseVideo', this.currentTime)
				}
				
			},
			screenchange(e){
				if(!e.detail.fullScreen){//如果退出全屏
					//停止播放
					this.videoContext.pause()
					this.isShow = false;
					this.$emit('pauseVideo', this.currentTime)
				}
			},
			screenclick(e){
				// this.videoContext.pause()
			},
			getBase64(url){
				this.bg_url = url
			}
		},
		beforeDestroy() {
			
		},
	}
	var getVideoCover = function(file, that){
		
		if(!that.src) {
			setTimeout(()=>{
				getVideoCover(that.src, that)
			}, 1000)
			return}
		that.newVal = {fullurl: file, width: that.width, height: that.height}
		
	}
</script>
<script module="canvas" lang="renderjs">
	export default {
		methods: {
			// 视图层创建base64图片
			create(newValue, oldValue, ownerInstance){
				
				let that = this
				// 第一次进入为空不操作
				if(newValue == null){
					return
				}
				// 在缓存中创建video标签
				var video = document.createElement("VIDEO")
				// 通过setAttribute给video dom元素添加自动播放的属性，因为视频播放才能获取封面图    
				// 设置video自动播放属性
				// video.autoplay = true
				// video.x5-video-player-type = "h5-page"  
				// video.webkit-playsinline="true" 
				// video.playsinline="true" 
				// video.x5-video-orientation="landscape|portrait"
				// 该设置方法无效
				video.setAttribute('autoplay', true)
				video.setAttribute('x5-video-player-type', 'h5-page')
				video.setAttribute('webkit-playsinline', true)
				video.setAttribute('playsinline', true)
				video.setAttribute('x5-video-orientation', 'landscape|portrait')
				// 再添加一个静音的属性，否则自动播放会有声音
				// 该设置方法无效
				// video.setAttribute('muted', true)
				video.muted = true
				// 如果报错Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
				// 可以把下面两行代码加上，因为我用的线上video url，所以可能抛出了异常。大概意思就是跨域了toDataURL()使用了外域资源
				video.setAttribute('crossOrigin', 'anonymous')
				video.crossOrigin = '*'
				// 上面我们只是创建了video标签，视频播放需要内部的source的标签，scr为播放源
				video.innerHTML = '<source src=' + newValue.fullurl + ' type="audio/mp4">'
				// 再创建canvas画布标签
				var canvas = document.createElement('canvas');
				var ctx = canvas.getContext('2d');
				// video注册canplay自动播放事件
				// 防止video不播放，所以手动加个播放操作
				video.play()
				// video播放事件
				video.addEventListener('canplay', ()=>{
					// 创建画布的宽高属性节点，就是图片的大小，单位PX
					let width = video.videoWidth*2,
						height = video.videoHeight*2
					var anw = document.createAttribute("width");
					anw.nodeValue = width;
					var anh = document.createAttribute("height");
					anh.nodeValue = height;
					canvas.setAttributeNode(anw);
					canvas.setAttributeNode(anh);
					// 画布渲染
					ctx.drawImage(video, 0, 0, width, height);
					// 生成base64图片，指定type为jpeg格式生成的图片base64编码会小很多
					var base64 = canvas.toDataURL('image/jpeg') // 这就是封面图片的base64编码
					// 传递数据给逻辑层
					// console.log(121, base64)
					// that.bg_url = base64
					ownerInstance.callMethod('getBase64',base64)
					// 删除创建的video 、canvas dom，要不然重新选取视频生成图片不生效
					// ps：开始有这个问题，但是后面不知道为什么又没有了，如果发现生成第一次base64之后再选择不生效，可以尝试一下把下方注释打开
					// document.body.removeChild(video)
					// document.body.removeChild(canvas)
				})
			}
		}
	}
</script>
<style>
.close{
	
}
</style>
